<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>证书参数配置</span>
        <el-button style="float: right; padding: 3px 0" link @click="goBack">返回列表</el-button>
      </div>

      <el-tabs v-model="activeTab">
        <el-tab-pane label="参数映射" name="mapping">
          <el-form :model="mappingForm" ref="mappingForm" label-width="120px">
            <el-form-item label="模板选择" prop="templateId">
              <el-select v-model="mappingForm.templateId" placeholder="请选择模板" @change="handleTemplateChange" style="width: 100%;">
                <el-option
                  v-for="item in templateOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <template v-if="mappingForm.templateId">
              <el-divider content-position="left">变量映射</el-divider>
              
              <el-table :data="paramMappings" border>
                <el-table-column prop="variableName" label="变量名" width="180"></el-table-column>
                <el-table-column prop="description" label="描述" width="180"></el-table-column>
                <el-table-column label="数据来源" width="200">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.sourceType" placeholder="选择数据来源" style="width: 100%;">
                      <el-option label="产品信息" value="product"></el-option>
                      <el-option label="批次信息" value="batch"></el-option>
                      <el-option label="检验数据" value="inspection"></el-option>
                      <el-option label="固定值" value="fixed"></el-option>
                      <el-option label="系统变量" value="system"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="映射字段">
                  <template slot-scope="scope">
                    <el-select 
                      v-if="scope.row.sourceType === 'product'" 
                      v-model="scope.row.sourceField" 
                      placeholder="选择产品字段"
                      style="width: 100%;"
                    >
                      <el-option label="产品名称" value="name"></el-option>
                      <el-option label="产品编号" value="code"></el-option>
                      <el-option label="产品规格" value="specification"></el-option>
                      <el-option label="产品材质" value="material"></el-option>
                      <el-option label="产品等级" value="grade"></el-option>
                    </el-select>
                    <el-select 
                      v-else-if="scope.row.sourceType === 'batch'" 
                      v-model="scope.row.sourceField" 
                      placeholder="选择批次字段"
                      style="width: 100%;"
                    >
                      <el-option label="批次号" value="batchNo"></el-option>
                      <el-option label="生产日期" value="productionDate"></el-option>
                      <el-option label="生产线" value="productionLine"></el-option>
                      <el-option label="数量" value="quantity"></el-option>
                    </el-select>
                    <el-select 
                      v-else-if="scope.row.sourceType === 'inspection'" 
                      v-model="scope.row.sourceField" 
                      placeholder="选择检验字段"
                      style="width: 100%;"
                    >
                      <el-option label="检验结果" value="inspectionResult"></el-option>
                      <el-option label="检验人员" value="inspector"></el-option>
                      <el-option label="检验日期" value="actualDate"></el-option>
                      <el-option label="检验项目" value="paramName"></el-option>
                      <el-option label="检验值" value="measuredValue"></el-option>
                    </el-select>
                    <el-select 
                      v-else-if="scope.row.sourceType === 'system'" 
                      v-model="scope.row.sourceField" 
                      placeholder="选择系统变量"
                      style="width: 100%;"
                    >
                      <el-option label="当前日期" value="currentDate"></el-option>
                      <el-option label="当前用户" value="currentUser"></el-option>
                      <el-option label="公司名称" value="companyName"></el-option>
                    </el-select>
                    <el-input 
                      v-else-if="scope.row.sourceType === 'fixed'" 
                      v-model="scope.row.fixedValue" 
                      placeholder="输入固定值"
                    ></el-input>
                    <span v-else>请先选择数据来源</span>
                  </template>
                </el-table-column>
                <el-table-column label="默认值" width="180">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.defaultValue" placeholder="默认值"></el-input>
                  </template>
                </el-table-column>
              </el-table>

              <div style="margin-top: 20px; text-align: center;">
                <el-button type="primary" @click="saveParamMappings">保存映射配置</el-button>
              </div>
            </template>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="自动生成规则" name="rules">
          <el-form :model="rulesForm" ref="rulesForm" label-width="120px">
            <el-form-item label="模板选择" prop="templateId">
              <el-select v-model="rulesForm.templateId" placeholder="请选择模板" @change="handleTemplateChangeForRules" style="width: 100%;">
                <el-option
                  v-for="item in templateOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <template v-if="rulesForm.templateId">
              <el-divider content-position="left">证书编号规则</el-divider>
              
              <el-form-item label="编号前缀">
                <el-input v-model="rulesForm.numberPrefix" placeholder="例如：QC-"></el-input>
              </el-form-item>
              
              <el-form-item label="编号格式">
                <el-select v-model="rulesForm.numberFormat" placeholder="请选择编号格式" style="width: 100%;">
                  <el-option label="前缀-年月日-序号" value="PREFIX-YYYYMMDD-SEQ"></el-option>
                  <el-option label="前缀-年月-序号" value="PREFIX-YYYYMM-SEQ"></el-option>
                  <el-option label="前缀-产品代码-序号" value="PREFIX-PRODUCT-SEQ"></el-option>
                  <el-option label="自定义格式" value="CUSTOM"></el-option>
                </el-select>
              </el-form-item>
              
              <el-form-item label="自定义格式" v-if="rulesForm.numberFormat === 'CUSTOM'">
                <el-input v-model="rulesForm.customFormat" placeholder="例如：{PREFIX}-{YYYY}{MM}{DD}-{SEQ}"></el-input>
                <div class="el-form-item-description">
                  可用变量：{PREFIX}=前缀, {YYYY}=年, {MM}=月, {DD}=日, {SEQ}=序号, {PRODUCT}=产品代码
                </div>
              </el-form-item>
              
              <el-form-item label="序号位数">
                <el-input-number v-model="rulesForm.seqDigits" :min="2" :max="6"></el-input-number>
              </el-form-item>
              
              <el-form-item label="序号重置规则">
                <el-radio-group v-model="rulesForm.seqResetRule">
                  <el-radio label="DAILY">每天重置</el-radio>
                  <el-radio label="MONTHLY">每月重置</el-radio>
                  <el-radio label="YEARLY">每年重置</el-radio>
                  <el-radio label="NEVER">永不重置</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-divider content-position="left">自动生成规则</el-divider>
              
              <el-form-item label="自动生成">
                <el-switch v-model="rulesForm.autoGenerate"></el-switch>
              </el-form-item>
              
              <el-form-item label="触发条件" v-if="rulesForm.autoGenerate">
                <el-checkbox-group v-model="rulesForm.triggers">
                  <el-checkbox label="INSPECTION_COMPLETE">检验完成时</el-checkbox>
                  <el-checkbox label="BATCH_COMPLETE">批次完成时</el-checkbox>
                  <el-checkbox label="MANUAL">手动触发</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              
              <div style="margin-top: 20px; text-align: center;">
                <el-button type="primary" @click="saveGenerationRules">保存生成规则</el-button>
              </div>
            </template>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="签名印章管理" name="signature">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-upload
                class="signature-uploader"
                action="/api/certificate/template/signature"
                :show-file-list="false"
                :on-success="handleSignatureSuccess"
                :before-upload="beforeSignatureUpload"
                :headers="uploadHeaders"
              >
                <img v-if="signatureImageUrl" :src="signatureImageUrl" class="signature-image">
                <i v-else class="el-icon-plus signature-uploader-icon"></i>
                <div class="el-upload__text">点击上传签名图片</div>
              </el-upload>
              <el-form :model="signatureForm" label-width="80px" style="margin-top: 20px;">
                <el-form-item label="签名名称">
                  <el-input v-model="signatureForm.name" placeholder="请输入签名名称"></el-input>
                </el-form-item>
                <el-form-item label="签名人">
                  <el-input v-model="signatureForm.signer" placeholder="请输入签名人"></el-input>
                </el-form-item>
                <el-form-item label="职位">
                  <el-input v-model="signatureForm.position" placeholder="请输入职位"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="saveSignature">保存签名</el-button>
                  <el-button @click="resetSignatureForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="12">
              <el-card shadow="never" class="box-card">
                <div slot="header" class="clearfix">
                  <span>签名列表</span>
                </div>
                <el-table :data="signatureList" style="width: 100%">
                  <el-table-column prop="name" label="名称" width="120"></el-table-column>
                  <el-table-column prop="signer" label="签名人" width="120"></el-table-column>
                  <el-table-column prop="position" label="职位"></el-table-column>
                  <el-table-column label="签名图片" width="120">
                    <template slot-scope="scope">
                      <el-image 
                        style="width: 80px; height: 40px"
                        :src="scope.row.imageUrl"
                        :preview-src-list="[scope.row.imageUrl]">
                      </el-image>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        link
                        @click="editSignature(scope.row)">编辑</el-button>
                      <el-button
                        size="mini"
                        link
                        @click="deleteSignature(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { listTemplate, getTemplate, listTemplateVariables, saveTemplateVariables, uploadSignature, listSignatures } from "@/api/certificate/template";
import { getToken } from "@/utils/auth";

export default {
  name: "TemplateParameter",
  data() {
    return {
      // 当前激活的标签页
      activeTab: 'mapping',
      // 模板选项
      templateOptions: [],
      // 参数映射表单
      mappingForm: {
        templateId: null
      },
      // 参数映射列表
      paramMappings: [],
      // 自动生成规则表单
      rulesForm: {
        templateId: null,
        numberPrefix: 'QC',
        numberFormat: 'PREFIX-YYYYMMDD-SEQ',
        customFormat: '',
        seqDigits: 4,
        seqResetRule: 'DAILY',
        autoGenerate: false,
        triggers: ['MANUAL']
      },
      // 签名表单
      signatureForm: {
        id: null,
        name: '',
        signer: '',
        position: '',
        imageUrl: ''
      },
      // 签名图片URL
      signatureImageUrl: '',
      // 签名列表
      signatureList: [],
      // 上传请求头
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      }
    };
  },
  created() {
    this.getTemplateList();
    this.getSignatureList();
  },
  methods: {
    // 获取模板列表
    getTemplateList() {
      listTemplate({ pageSize: 100 }).then(response => {
        this.templateOptions = response.rows || [];
      });
    },
    // 获取签名列表
    getSignatureList() {
      listSignatures().then(response => {
        this.signatureList = response.data || [];
      });
    },
    // 返回列表
    goBack() {
      this.$router.push('/certificate/template');
    },
    // 模板变更处理(参数映射)
    handleTemplateChange(templateId) {
      if (templateId) {
        // 获取模板变量
        listTemplateVariables(templateId).then(response => {
          const variables = response.data || [];
          this.paramMappings = variables.map(v => ({
            variableName: v.name,
            description: v.description,
            sourceType: '',
            sourceField: '',
            fixedValue: '',
            defaultValue: v.defaultValue || ''
          }));
        });
      } else {
        this.paramMappings = [];
      }
    },
    // 模板变更处理(自动生成规则)
    handleTemplateChangeForRules(templateId) {
      if (templateId) {
        // 获取模板生成规则
        getTemplate(templateId).then(response => {
          const template = response.data || {};
          if (template.generateRules) {
            try {
              const rules = JSON.parse(template.generateRules);
              this.rulesForm = { ...this.rulesForm, ...rules, templateId };
            } catch (e) {
              console.error('解析生成规则失败', e);
            }
          }
        });
      }
    },
    // 保存参数映射
    saveParamMappings() {
      if (!this.mappingForm.templateId) {
        this.$message.warning('请先选择模板');
        return;
      }

      // 检查必填项
      let valid = true;
      this.paramMappings.forEach(mapping => {
        if (!mapping.sourceType) {
          valid = false;
        } else if (mapping.sourceType !== 'fixed' && !mapping.sourceField) {
          valid = false;
        } else if (mapping.sourceType === 'fixed' && !mapping.fixedValue) {
          valid = false;
        }
      });

      if (!valid) {
        this.$message.warning('请完成所有映射配置');
        return;
      }

      // 保存映射配置
      saveTemplateVariables({
        templateId: this.mappingForm.templateId,
        mappings: this.paramMappings
      }).then(() => {
        this.$message.success('参数映射保存成功');
      });
    },
    // 保存生成规则
    saveGenerationRules() {
      if (!this.rulesForm.templateId) {
        this.$message.warning('请先选择模板');
        return;
      }

      // 检查自定义格式
      if (this.rulesForm.numberFormat === 'CUSTOM' && !this.rulesForm.customFormat) {
        this.$message.warning('请输入自定义格式');
        return;
      }

      // 保存生成规则
      const templateData = {
        id: this.rulesForm.templateId,
        generateRules: JSON.stringify({
          numberPrefix: this.rulesForm.numberPrefix,
          numberFormat: this.rulesForm.numberFormat,
          customFormat: this.rulesForm.customFormat,
          seqDigits: this.rulesForm.seqDigits,
          seqResetRule: this.rulesForm.seqResetRule,
          autoGenerate: this.rulesForm.autoGenerate,
          triggers: this.rulesForm.triggers
        })
      };

      // 调用更新模板API
      this.$modal.confirm('确认保存生成规则？').then(() => {
        return updateTemplate(templateData);
      }).then(() => {
        this.$message.success('生成规则保存成功');
      });
    },
    // 上传签名前的处理
    beforeSignatureUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传签名图片只能是图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传签名图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    // 签名上传成功处理
    handleSignatureSuccess(response, file) {
      this.signatureImageUrl = URL.createObjectURL(file.raw);
      if (response.code === 200) {
        this.signatureForm.imageUrl = response.data;
      } else {
        this.$message.error('上传失败: ' + response.msg);
      }
    },
    // 保存签名
    saveSignature() {
      if (!this.signatureForm.name) {
        this.$message.warning('请输入签名名称');
        return;
      }
      if (!this.signatureForm.imageUrl) {
        this.$message.warning('请上传签名图片');
        return;
      }

      // 保存签名信息
      const data = { ...this.signatureForm };
      uploadSignature(data).then(response => {
        this.$message.success('签名保存成功');
        this.getSignatureList();
        this.resetSignatureForm();
      });
    },
    // 重置签名表单
    resetSignatureForm() {
      this.signatureForm = {
        id: null,
        name: '',
        signer: '',
        position: '',
        imageUrl: ''
      };
      this.signatureImageUrl = '';
    },
    // 编辑签名
    editSignature(row) {
      this.signatureForm = { ...row };
      this.signatureImageUrl = row.imageUrl;
    },
    // 删除签名
    deleteSignature(row) {
      this.$modal.confirm('确认删除该签名？').then(() => {
        // 调用删除签名API
        return deleteSignature(row.id);
      }).then(() => {
        this.$message.success('删除成功');
        this.getSignatureList();
      });
    }
  }
};
</script>

<style scoped>
.signature-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  text-align: center;
  padding: 20px;
}
.signature-uploader:hover {
  border-color: #409EFF;
}
.signature-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 40px;
  line-height: 40px;
  text-align: center;
}
.signature-image {
  width: 178px;
  height: 80px;
  display: block;
  object-fit: contain;
}
.el-form-item-description {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 